package org.example.RabbitMq.amqpService.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.Constant.RabbitConstant;
import org.example.RabbitMq.amqpService.IdGeneratorService;
import org.example.RabbitMq.amqpService.TableCacheSender;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @Author : zhangbo
 * @data : 2024/7/12
 * @description :
 */
@Service
@Slf4j
public class TableCacheSenderImpl implements TableCacheSender {
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public <T> void sendResetMsg(List<T> list, String routingKey) {
        String uuid = idGeneratorService.getModelPrimaryKey();
        CorrelationData correlationId = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(RabbitConstant.Exchange.DIRECT, routingKey, list, message -> {
            //设置消息持久化
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            return message;
        }, correlationId);
    }

    @Override
    public <T> void sendResetMsg(String MessageQueueName, List<T> list, String routingKey) {
        String uuid = idGeneratorService.getModelPrimaryKey();
        CorrelationData correlationId = new CorrelationData(uuid);
        //消息生产者
        rabbitTemplate.convertAndSend(RabbitConstant.Exchange.DIRECT, routingKey, list, message -> {
            //设置消息持久化
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            message.getMessageProperties().setHeader("MessageQueueName", MessageQueueName);
            return message;
        }, correlationId);
    }

    @Override
    public <T> void sendDelayMsg(String MessageQueueName, List<T> list, String routingKey, Long delayTimes) {
        String uuid = idGeneratorService.getModelPrimaryKey();
        log.info("发送延时消息,MessageQueueName={},routingKey={},delayTimes={},msgId={},msg={}",MessageQueueName, routingKey, delayTimes, uuid, list);
        CorrelationData correlationId = new CorrelationData(uuid);
        rabbitTemplate.convertAndSend(RabbitConstant.Exchange.DIRECT, routingKey, list, message -> {
            //设置消息持久化
            message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            message.getMessageProperties().setHeader("MessageQueueName", MessageQueueName);
            //延迟消息
            message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
            return message;
        }, correlationId);
    }
}
